<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="品牌名称" prop="name">
        <el-input
          placeholder="请输入品牌名称"
          clearable
          v-model="queryParams.name"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" v-on:click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" v-on:click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" v-on:click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="[`product:brand:update`]"
          >修改</el-button
        ><!--- 不能加(),因为点击时候会传递空参数 -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="[`product:brand:remove`]"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table
      :data="brandList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌名称" prop="name" width="200" />
      <el-table-column label="品牌图标" prop="logo" #default="scope">
        <img :src="scope.row.logo" width="50" />
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            v-on:click="handleUpdate(scope.row)"
            v-hasPermi="[`product:brand:update`]"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            v-on:click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination v-show="total > 0" :total="total" />

    <!-- 新增或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="brandRef" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌图标" prop="logo">
          <el-upload
            class="avatar-uploader"
            :action="imgUpload.url"
            :headers="imgUpload.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup name="Brand">
import {
  listBrand,
  addBrand,
  updateBrand,
  delBrand,
  getBrand,
} from "@/api/product/brand.js";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();

//定义分页列表数据模型
const brandList = ref([]);
//定义列表总记录数模型
const total = ref(2);
// 查询请求参数和其他参数(表单参数)等模型封装
// reactive定义：对象（或数组）数据类型，则适用于复杂对象或数组的响应式数据
const data = reactive({
  //定义搜索模型
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
  },
  form: {
    id: null,
    name: null,
    logo: null,
  },
  imgUpload: {
    url: import.meta.env.VITE_APP_BASE_API + "/file/upload",
    headers: {
      Authorization: "Bearer " + getToken(),
    },
  },
  rules:{
    name: [{ required: true, message: "品牌不能为空", trigger: "blur" }],// 在失去光标后校验当前输入框是否为空
    logo: [{ required: true, message: "品牌LOGO不能为空", trigger: "blur" }],// 在失去光标后校验当前输入框是否为空
  }
});
const { queryParams, form, imgUpload,rules } = toRefs(data); // 将reactive复合型对象中的具体内容提出出来编程一个普通的响应式对象

const open = ref(false);
const title = ref("新增");

//加载数据时显示的动效控制模型
const loading = ref(true);
const multiple = ref(true);
const single = ref(true);
const ids = ref([]);
/**********************************************************************************************************************/

// 数据表格选中状态
function handleSelectionChange(rowSelect) {
  // 保存点击的行id
  ids.value = rowSelect.map((item) => item.id); // 可能是单值，也可能是数组

  // 当xxx的时候修改按钮不可用
  single.value = rowSelect.length != 1;

  // 当xxx的时候删除按钮不可用
  multiple.value = rowSelect.length === 0;

  console.log("ids==============================", ids.value);
}

// 删除按钮操作
function handleDelete(row) {
  // 从功能栏删除点击过来的请求row是undefined

  const _ids = row.id || ids.value; // 如果从当前行点击则row.id，如果row.id是undefined说明是从功能栏点击过来的

  ElMessageBox.confirm(
    '是否确认删除分类品牌编号为"' + _ids + '"的数据项？', // 提示信息
    "系统提示", // 框体标题
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(function () {
      delBrand(_ids).then(() => {
        ElMessage.success("删除成功");
        getList();
      });
    })
    .catch(() => {
      ElMessage.error("取消操作");
    });
}

// 修改
function handleUpdate(row) {
  console.log(row)
  if (row.id) {
    form.value = { ...row };
  } else {
    const _id = ids.value[0];
    getBrand(_id).then((resposne) => {
      form.value = resposne.data;
    });
  }
  open.value = true;
  title.value = "修改";
}

// 删除

// 提交表单
async function submitForm() {
  // 设置返回结果
  let _response = null;

  if (form.value.id) {
    _response = await updateBrand(form.value);
  } else {
    _response = await addBrand(form.value);
  }

  // 提交后的提示
  let code = _response.code;
  let msg = _response.msg;
  if (code === 200) {
    ElMessage.success(msg);
    open.value = false;
    getList();
  }

  // 另一种写法
  //   // 修改
  //   updateBrand(form.value).then((response) => {
  //     _response = response;
  //   });
  // } else {
  //   // 新增
  //   addBrand(form.value).then((response) => {
  //     _response = response;
  //   });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

//***上传回显 */
function handleAvatarSuccess(response, file) {
  let url = response.data.url;
  form.value.logo = url;
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    logo: null,
  };
}

/** 新增显示对话框 **/
function handleAdd() {
  // 设置对话框显示属性
  // 清理表单
  reset();
  open.value = true;
  title.value = "新增";
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.name = null;
  handleQuery();
}

const getList = function () {
  loading.value = true;
  // alert("调用用户列表api")
  // let {total,rows,code,msg} = await listBrand();
  listBrand(queryParams.value).then((response) => {
    let num = response.total; // 多少行数据
    let data = response.rows;
    brandList.value = data;
    total.value = num;
    loading.value = false;
  });
};

getList();
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>